$(function () {
    var version="0.0.1";
    var device="wap";
    var isTyping = false;
    var sender = $("#sendButton");
    var connect = $("#connectButton");
    var messageInput = $("#messageInput");
    var uid = "";
    var subSocket = null;
	var servers = [];
    var _selected_server = null;
	
    var me = '<div class="meC"><img src="img/img_tx.png" alt="" class="i_msg" /><div class="mC"><div class="mI"><div class="mI2">[:::]</div></div><div class="msj"></div></div></div>';
    var stranger = '<div class="robotC"><img src="img/img_tx.png" alt="" class="i_msg2" /><div class="yC"><div class="yI"><div class="yI2">[:::]</div></div><div class="msj2"></div></div></div>';
    var notice ='<div class="infoC">[:::]</div>';
    var noticefr ='<div class="infoC fr">[:::]</div>';
	var noticetyping ='<div id="typingDiv" class="infoC fr" style="display:none;"><i class="i_pen"></i>对方正在输入...</div>';

	$("#message").append(noticetyping);
	
	display2("获取服务器信息，请稍等","notice");
    jQuery.ajax({
        url: "http://chat.xiaohuangji.com/servers/"+device,
        dataType: "json",
        async:false,
        success: function(json){
            servers = json.servers;
            var _index2 = json.sp_server;
            _selected_server = servers[_index2];
        },
        complete: function(){
        },
        error: function(){
            display2("网络状况不给力，请关闭页面，重新爱抚小黄鸡。","notice");
        }
    });
    
    if(null == _selected_server){
        display2("网络状况不给力，请关闭页面，重新爱抚小黄鸡。","notice");
        return;
    }
	
	display2("左下角为(离开|寻人)切换键","notice");
	
	function _server(){
        return _selected_server+"/event";
    } 
	
    var request = {
        url: _server(),
        contentType : "application/json",
        transport : 'websocket' ,
        fallbackTransport: 'long-polling',
        reconnectInterval: 5000,
            onMessage: function(response) {
			console.log(response.responseBody);
            var msg = eval("("+response.responseBody+")");
            if(msg.type == "join") {
                display2("陌生人加入聊天","notice");
                messageInput.attr("disabled",false).focus();
                sender.attr("disabled",false);
                connect.removeClass("an_xz").addClass("an_esc");
            } else if(msg.type == "leave") {
				display2("对方已离开，请稍等，继续寻人中","noticefr");
            } else if(msg.type == "message") {
                display2(msg.data,"stranger");
            }else if(msg.type == "typing") {
                display2("对方正在输入...","noticetyping");
            }else if(msg.type == "error") {
                display2("抱歉请您重刷页面","notice");
            }
        },
        onOpen: function(response) {
            uid = response.request.uuid;
            joining();
            messageInput.attr("disabled",false).focus();
            sender.attr("disabled",false);
            connect.removeClass("an_xz").addClass("an_esc");
        },
        onReconnect: function (request, response) {
           // status.text("Reconnecting...");
        },
        onClose: function(response) {
            //connect.attr("disabled",true);
        },

        onError: function(response) {
            //status.text("Problems with socket or server is down");
        },
        onClientTimeout:function(response){
            display2("对话已超时","notice");
            connect.attr("disabled",true);
            messageInput.attr("disabled",true);
        }

    };

    var socket = atmosphere;

    connect.click(function(){
        if(connect.hasClass("an_esc")){
            display2("您已离开本次对话","notice");
            leave();
            connect.removeClass("an_esc").addClass("an_xz");
            connect.attr("disabled",false);
			if(null!=subSocket){
				subSocket.close();
			}
        }else if(connect.hasClass("an_xz")){
            display2("请您稍等，正在寻人..","notice");
            subSocket = socket.subscribe(request);
        }
    });

    sender.click(function(){
        message();
    });

    messageInput.bind("keypress", function(e) {
        var kcode = e.keyCode || e.which;
        if(kcode==13) {
            message();
        }else{
            typing();
        }
    });
	
	//表情
	$(".an_bq").click(function(){
        $(".c_bq").toggle();
    });
	
	$(".c_bq a").click(function(){
        var id=/\d+/.exec($(this).find("img").attr("src"))[0];
        messageInput.val(messageInput.val()+"[:"+id+"]");
    });
	
	function unwrap(message){
        return message.replace(/\[:(\d+)\]/g,"<img src=\"img/face/bq_$1.gif\">");
    }
	
	
    function typing(){
		if(!isTyping){
			var msg = {
			    ver:version,
                device:device,
				type: "typing",
				uid:uid
			}
			subSocket.push(JSON.stringify(msg));
			isTyping=true;
		}
    }

    function joining(){
        var msg = {
			ver:version,
            device:device,
            type: "join",
            uid:uid
        }
        subSocket.push(JSON.stringify(msg));
    }

    function leave(){
        var msg = {
			ver:version,
            device:device,
            type: "leave",
            uid:uid
        }
        subSocket.push(JSON.stringify(msg));
    }

    function message() {
        if(!messageInput.val().trim()) {
            return;
        }

        var msg = {
			ver:version,
            device:device,
            type: "message",
            data: messageInput.val(),
            uid:uid
        }
		
		if(messageInput.val().length<250) {
			display2(msg.data,"me");
			subSocket.push(JSON.stringify(msg));
			messageInput.val("");
        }else{
		    display2("一休哥，您输入的字太多啦，休息一下 69！","notice");
		}
		$("#typingDiv").hide();
        isTyping=false;
		$(".c_bq").hide();
    }
    
    function display2(message,type){
        var msg ="";
        switch(type){
            case 'stranger': msg = stranger; break;
            case 'me': msg = me; break;
            case 'notice': msg = notice; break;
			case 'noticefr': msg = noticefr; break;
			case 'noticetyping': {
				$("#message").append($("#typingDiv").show());
                $("#message_wrapper").scrollTop($("#message").height());
				return;
			};
        }
        
        msg=msg.replace(/\[:::\]/g,message);
        $("#message").append(unwrap(msg));
        $("#message_wrapper").scrollTop($("#message").height());
    }	
	$(window).resize(function() {
		$("#message_wrapper").scrollTop($("#message").height());
	});
    display2("请您稍等，正在寻人..","notice");
    //定时1秒
    setTimeout(function(){
        subSocket = socket.subscribe(request);
    },200);
});